package com.javen.controller;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.jfinal.log.Log;

@ServerEndpoint(value ="/websocket")
public class WebSocketController {
	static Log log = Log.getLog(WebSocketController.class);
	private static final String GUEST_PREFIX = "Guest"; 
	private static final AtomicInteger connectionIds = new AtomicInteger(0);  
    private static final Set<WebSocketController> connections = new CopyOnWriteArraySet<>();  
  
    private String nickname=null;  
    private Session session;  
	
    
    public WebSocketController() {  
        nickname = GUEST_PREFIX + connectionIds.getAndIncrement();  
    }  
	
	@OnOpen
	public void onOpen(Session session) {
		this.session = session;  
		connections.add(this); 
		 
		System.out.println("*** WebSocket opened from sessionId " + session.getId());
		String message = String.format("* %s %s", nickname, "has joined.");  
        broadcast(message);
	}

	@OnClose
	public void onClose(Session session) {
		System.out.println("*** WebSocket closed from sessionId " + session.getId());
		connections.remove(this);  
        String message = String.format("* %s %s",nickname, "has disconnected.");  
        broadcast(message);
	}

	@OnMessage
	public void onMessage(String message, Session session) {
			System.out.println("接收到的数据为："+message+" from sessionId "+session.getId());
			String response = String.format("* %s %s",nickname, message);  
			broadcast(response);  
	}
	
	
	private static void broadcast(String msg) {  
        for (WebSocketController client : connections) {  
            try {  
                synchronized (client) {  
                    client.session.getBasicRemote().sendText(msg);  
                }  
            } catch (IOException e) {  
                System.out.println("Chat Error: Failed to send message to client");  
                connections.remove(client);  
                try {  
                    client.session.close();  
                } catch (IOException e1) {  
                    // Ignore  
                }  
                String message = String.format("* %s %s",  
                        client.nickname, "has been disconnected.");  
                broadcast(message);  
            }  
        }  
    }  
}